<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
			label-width="68px">
<!--			<el-form-item label="排序" prop="sort">-->
<!--				<el-input v-model="queryParams.sort" placeholder="请输入排序" clearable @keyup.enter.native="handleQuery" />-->
<!--			</el-form-item>-->
			<!-- <el-form-item label="是否显示" prop="isShow">
				<el-input v-model="queryParams.isShow" placeholder="请输入0：不显示 1：显示" clearable
					@keyup.enter.native="handleQuery" />
			</el-form-item> -->
			<!-- <el-form-item label="0：不删除 1：删除" prop="isDel">
				<el-input v-model="queryParams.isDel" placeholder="请输入0：不删除 1：删除" clearable
					@keyup.enter.native="handleQuery" />
			</el-form-item> -->
			<!-- <el-form-item label="创建时间" prop="createrTime">
				<el-date-picker clearable v-model="queryParams.createrTime" type="date" value-format="yyyy-MM-dd"
					placeholder="请选择创建时间">
				</el-date-picker>
			</el-form-item> -->
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
					v-hasPermi="['system:banner:add']">新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
					v-hasPermi="['system:banner:edit']">修改</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
					@click="handleDelete" v-hasPermi="['system:banner:remove']">删除</el-button>
			</el-col>
			<!-- <el-col :span="1.5">
				<el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
					v-hasPermi="['system:banner:export']">导出</el-button>
			</el-col> -->
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<el-table v-loading="loading" :data="bannerList" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="轮播图名称" align="center" prop="bannarName" />
			<el-table-column label="轮播图" align="center" prop="bannarUrl">
				<template slot-scope="scope">
					<el-image
					      style="width: 100px; height: 100px"
					      :src="scope.row.bannarUrl"
					      :zoom-rate="1.2"
					      :max-scale="7"
					      :min-scale="0.2"
					      :initial-index="4"
					      fit="cover"
					    />
				</template>
			</el-table-column>
			<el-table-column label="排序" align="center" prop="sort" />
			<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
				<template slot-scope="scope">
					<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
						v-hasPermi="['system:banner:edit']">修改</el-button>
					<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
						v-hasPermi="['system:banner:remove']">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
			@pagination="getList" />

		<!-- 添加或修改【请填写功能名称】对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
			<el-form ref="form" :model="form" :rules="rules" label-width="80px">
				<el-form-item label="名称" prop="bannarName">
					<el-input v-model="form.bannarName" placeholder="请输入轮播图名称" />
				</el-form-item>
				<el-form-item label="排序" prop="sort">
					<el-input-number v-model="form.sort" placeholder="请输入排序"></el-input-number>
				</el-form-item>
				<el-form-item label="上传图片" prop="bannarUrl">
					<!-- <ImageUpload v-model="form.bannarUrl" :limit="1" @input="input"></ImageUpload> -->
					<!-- <el-upload ref="field101" :file-list="field101fileList" :action="field101Action"
						:before-upload="field101BeforeUpload">
						<el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
					</el-upload> -->
					<el-upload list-type="picture" action="" accept=".jpg, .png" :limit="1" :auto-upload="false"
						:file-list="fileList" :on-change="changeFile">
						<el-button size="small" type="primary">上传图片</el-button>
						<div slot="tip" class="el-upload__tip">只能上传一张.jpg/.png文件</div>
					</el-upload>
				</el-form-item>
<!--				<el-form-item label="创建时间" prop="createrTime">-->
<!--				  <el-date-picker clearable-->
<!--				    v-model="form.createrTime"-->
<!--				    type="date"-->
<!--				    value-format="yyyy-MM-dd"-->
<!--				    placeholder="请选择创建时间">-->
<!--				  </el-date-picker>-->
<!--				</el-form-item>-->
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import {
		listBanner,
		getBanner,
		delBanner,
		addBanner,
		updateBanner
	} from "@/api/system/banner";
	import {
		upload,
		getUpload
	} from "@/api/system/upload";
	export default {
		name: "Banner",
		data() {
			return {
				// 遮罩层
				loading: true,
				// 选中数组
				ids: [],
				// 非单个禁用
				single: true,
				// 非多个禁用
				multiple: true,
				// 显示搜索条件
				showSearch: true,
				// 总条数
				total: 0,
				// 【请填写功能名称】表格数据
				bannerList: [],
				// 弹出层标题
				title: "",
				// 是否显示弹出层
				open: false,
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					bannarName: null,
					bannarUrl: null,
					sort: null,
					isShow: null,
					isDel: 0,
					createrTime: null
				},
				// 表单参数
				form: {},
				// 表单校验
				rules: {
					bannarName: [{
						required: true,
						message: "轮播图名称不能为空",
						trigger: "blur"
					}],
					bannarUrl: [{
						required: true,
						message: "轮播图地址不能为空",
						trigger: "blur"
					}],
					sort: [{
						required: true,
						message: "排序不能为空",
						trigger: "blur"
					}],
					isShow: [{
						required: true,
						message: "0：不显示 1：显示不能为空",
						trigger: "blur"
					}],
					isDel: [{
						required: true,
						message: "0：不删除 1：删除不能为空",
						trigger: "blur"
					}],
					createrTime: [{
						required: true,
						message: "创建时间不能为空",
						trigger: "blur"
					}],
					bannarImage: [{
						required: true,
						message: "图片不能为空",
						trigger: "blur"
					}]
				},
				obj:{},
				fileList:[],
				field101Action: 'https://jsonplaceholder.typicode.com/posts/',
				field101fileList: [],
			};
		},
		created() {
			this.getList();
		},
		methods: {
			/** 查询【请填写功能名称】列表 */
			getList() {
				var that = this;
				this.loading = true;
				that.obj = {}
				that.bannerList = []
				listBanner(this.queryParams).then(response => {
					this.bannerList = response.rows;
					this.total = response.total;
					this.loading = false;
				});
			},
			getLoadImg(item,uid){
				var that = this;
				var obj = {}
				getUpload(uid).then((resp) => {
					// console.log("111"+resp.data.fileBase64)
					obj.id = item.id
					obj.sort = item.sort
					obj.createrTime = item.createrTime
					obj.bannarName = item.bannarName
					obj.isDel = item.isDel
          obj.isShow = item.isShow
					obj.bannarUrl = resp.data.fileBase64;
					that.bannerList.push(obj);
					// return resp.data.fileBase64;
				}).catch((e) => {
					that.$message.error(e.message);
					that.$refs.upload.clearFiles();
				})
			},
			// 文件状态改变时的钩子
			changeFile(file, fileList) {
				var that = this
				// this.form.photoUrl = []; // 表单绑定值
				// console.log("file"+JSON.stringify(file.uid))
				fileList.forEach(async item => {
					const img = await this.getBase64(item.raw);
					upload({
						fileBase64: img
					}).then((resp) => {
						console.log("resp" + resp)
						that.getImgUpload(resp.data.fileId)
						// this.form.photoUrl = resp.url;
					}).catch((e) => {
						this.$message.error(e.message);
						this.$refs.upload.clearFiles();
					})
				});
			},
			// 下载图片通过uuid
			getImgUpload(uid) {
				var that = this;
				getUpload(uid).then((resp) => {
					// console.log("resp" + resp)
					that.form.bannarUrl = resp.data.fileId;

				}).catch((e) => {
					that.$message.error(e.message);
					that.$refs.upload.clearFiles();
				})
			},
			// 图片转Base64
			getBase64(file) {
				return new Promise((resolve, reject) => {
					const reader = new FileReader();
					let imgBase64 = '';
					reader.readAsDataURL(file);
					reader.onload = () => {
						imgBase64 = reader.result;
					};
					reader.onerror = error => reject(error);
					reader.onloadend = () => resolve(imgBase64);
				});
			},
			// 取消按钮
			cancel() {
				this.open = false;
				this.reset();
			},
			// 表单重置
			reset() {
				this.form = {
					id: null,
					bannarName: null,
					bannarUrl: null,
					sort: null,
					isShow: null,
					isDel: null,
					createrTime: null
				};
				this.resetForm("form");
			},
			input(e) {
				console.log(e)
			},
			/** 搜索按钮操作 */
			handleQuery() {
				this.queryParams.pageNum = 1;
				this.getList();
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.resetForm("queryForm");
				this.handleQuery();
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.ids = selection.map(item => item.id)
				this.single = selection.length !== 1
				this.multiple = !selection.length
			},
			/** 新增按钮操作 */
			handleAdd() {
				this.reset();
                this.fileList = [];
				this.open = true;
				this.title = "添加【请填写功能名称】";
			},
			/** 修改按钮操作 */
			handleUpdate(row) {
				this.reset();
				const id = row.id || this.ids
				getBanner(id).then(response => {
					this.form = response.data;
					this.fileList.push(response.data.bannarUrl)
					this.open = true;
					this.title = "修改【请填写功能名称】";
				});
			},
			/** 提交按钮 */
			submitForm() {
        console.log(this.form)
				this.$refs["form"].validate(valid => {
					if (valid) {
						if (this.form.id != null) {
							updateBanner(this.form).then(response => {
								this.$modal.msgSuccess("修改成功");
								this.open = false;
								this.getList();
							});
						} else {
							addBanner(this.form).then(response => {
								this.$modal.msgSuccess("新增成功");
								this.open = false;
								this.getList();
							});
						}
					}
				});
			},
			field101BeforeUpload(file) {
				let isRightSize = file.size / 1024 / 1024 < 2
				if (!isRightSize) {
					this.$message.error('文件大小超过 2MB')
				}
				return isRightSize
			},
			/** 删除按钮操作 */
			handleDelete(row) {
				const ids = row.id || this.ids;
				this.$modal.confirm('是否确认删除【请填写功能名称】编号为"' + row.bannarName + '"的数据项？').then(function() {
					return delBanner(ids);
				}).then(() => {
					this.getList();
					this.$modal.msgSuccess("删除成功");
				}).catch(() => {});
			},
			/** 导出按钮操作 */
			handleExport() {
				this.download('system/banner/export', {
					...this.queryParams
				}, `banner_${new Date().getTime()}.xlsx`)
			},
			dowloadUrl(data) {
				download(data).then(response => {

				});
			},
		}
	};
</script>
